package org.yxt.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.yxt.springcloud.entities.CommonResult;

/**
 * 集成ribbon
 */
@RestController
@RequestMapping(value = "consumer")
public class SentinelConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 远程访问
     *
     * @return
     */
    @GetMapping("payment")
    public CommonResult payment() {
        CommonResult result = restTemplate.getForObject("http://cloud-alibaba-sentinel-provider-payment/sentinel/payment", CommonResult.class);
        return result;
    }

    /**
     * 服务降级
     *
     * @param number
     * @return
     */
    @GetMapping(value = "fallback/{number}")
    @SentinelResource(value = "fallback", fallback = "fallBackHandler", blockHandler = "blockExceptionHandler")
    public CommonResult fallback(@PathVariable int number) {
        CommonResult result = restTemplate.getForObject("http://cloud-alibaba-sentinel-provider-payment/sentinel/fallback/" + number, CommonResult.class);
        return result;
    }

    // 异常兜底 服务降级
    public CommonResult fallBackHandler(int number, Throwable throwable) {
        return new CommonResult(0, "sentinel 服务fallback兜底 异常 " + throwable);
    }

    // 异常兜底 服务限流
    public CommonResult blockExceptionHandler(int number, BlockException throwable) {
        return new CommonResult(0, "sentinel 服务blockException兜底 异常 " + throwable);
    }
}
